(function(){
  'use strict';

  if (!window.AppApi) return;

  var entryCard = document.getElementById('admin-strategy-mgr-entry');
  var openBtn = document.getElementById('btn-open-strategy-mgr');
  var viewCard = document.getElementById('admin-strategy-mgr-view');
  var backBtn = document.getElementById('btn-mgr-back');
  var createBtn = document.getElementById('btn-mgr-create');
  var listWrap = document.getElementById('strategy-mgr-list');
  var modal = document.getElementById('strategy-mgr-modal');
  var modalTitle = document.getElementById('mgr-modal-title');
  var formWrap = document.getElementById('strategy-mgr-form');
  var filterBar = null; var pagerBar = null;
  var state = { page: 1, page_size: 10, name: '', symbol: '', market_type: '', status: '', order: 'desc' };

  if (!entryCard || !openBtn || !viewCard || !backBtn || !createBtn || !listWrap) return;

  function show(el, yes){ if (!el) return; el.classList.toggle('is-hidden', !yes); el.style.display = yes ? '' : el.style.display; }

  async function ensureAdminOrFail(){
    try {
      var me = await window.AppApi.jsonOrThrow(await window.AppApi.request('GET','/auth/me', null, true));
      var ok = !!(me && (me.role === 'admin' || me.is_admin));
      if (!ok) throw new Error('not_admin');
      return true;
    } catch (e) {
      alert('需要管理员权限');
      return false;
    }
  }

  function cardEl(cls, title){
    var c = document.createElement('section'); c.className = 'card ' + (cls||'');
    if (title){ var h = document.createElement('h3'); h.className = 'card-title'; h.textContent = title; c.appendChild(h); }
    return c;
  }

  function buildRow(label, value){
    var d = document.createElement('div'); d.className = 'field';
    var l = document.createElement('label'); l.textContent = label; var i = document.createElement('input'); i.className='input'; i.value = value == null ? '' : String(value); i.readOnly = true;
    d.appendChild(l); d.appendChild(i); return d;
  }

  async function loadList(){
    if (listWrap) listWrap.innerHTML = '<p class="muted">加载中...</p>';
    try{
      var q = [];
      if (state.page) q.push('page=' + encodeURIComponent(state.page));
      if (state.page_size) q.push('page_size=' + encodeURIComponent(state.page_size));
      if (state.name) q.push('name=' + encodeURIComponent(state.name));
      if (state.symbol) q.push('symbol=' + encodeURIComponent(state.symbol));
      if (state.market_type) q.push('market_type=' + encodeURIComponent(state.market_type));
      if (state.status) q.push('status=' + encodeURIComponent(state.status));
      if (state.order) q.push('order=' + encodeURIComponent(state.order));
      var path = '/scripts' + (q.length ? ('?' + q.join('&')) : '');
      var res = await window.AppApi.request('GET', path, null, true);
      var data = await window.AppApi.jsonOrThrow(res);
      var items = Array.isArray(data) ? data : (data.items || []);
      renderList(items);
      renderPager(data);
    }catch(err){
      if (listWrap) listWrap.innerHTML = '<p class="muted">加载失败</p>';
      if (pagerBar) pagerBar.innerHTML = '';
    }
  }

  function renderList(items){
    listWrap.innerHTML = '';
    if (!items.length){ listWrap.innerHTML = '<p class="muted">暂无策略</p>'; return; }
    for (var i=0;i<items.length;i++){
      (function(item){
        var wrap = cardEl('', null);
        var header = document.createElement('div'); header.style.display='flex'; header.style.justifyContent='space-between'; header.style.alignItems='center';
        var title = document.createElement('div'); title.textContent = (item.name || '未命名') + ' · ' + (item.symbol || '');
        var actions = document.createElement('div');
        var toggleBtn = document.createElement('button'); toggleBtn.className='btn'; toggleBtn.textContent='展开';
        actions.appendChild(toggleBtn);
        header.appendChild(title); header.appendChild(actions); wrap.appendChild(header);

        var body = document.createElement('div'); body.style.display='none'; body.style.marginTop='8px';
        body.appendChild(buildRow('名称', item.name));
        body.appendChild(buildRow('符号', item.symbol));
        body.appendChild(buildRow('市场类型', item.market_type));
        (function(){
          var f=document.createElement('div'); f.className='field';
          var l=document.createElement('label'); l.textContent='状态';
          var wrapSwitch=document.createElement('div'); wrapSwitch.style.display='flex'; wrapSwitch.style.alignItems='center'; wrapSwitch.style.gap='8px';
          var sw=document.createElement('input'); sw.type='checkbox'; sw.setAttribute('role','switch'); sw.checked = (item.status === 'active' || item.enabled);
          sw.disabled = true; // 只展示，不直接切换
          var swLabel=document.createElement('span'); swLabel.textContent = sw.checked ? '启用' : '停用';
          wrapSwitch.appendChild(sw); wrapSwitch.appendChild(swLabel);
          f.appendChild(l); f.appendChild(wrapSwitch); body.appendChild(f);
        })();
        body.appendChild(buildRow('创建时间', item.created_at));

        var rowBtns = document.createElement('div'); rowBtns.style.display='flex'; rowBtns.style.gap='8px';
        var btnEdit = document.createElement('button'); btnEdit.className='btn'; btnEdit.textContent='修改';
        var btnDelete = document.createElement('button'); btnDelete.className='btn'; btnDelete.textContent='删除';
        var btnReveal = document.createElement('button'); btnReveal.className='btn'; btnReveal.textContent='查看秘钥';
        var btnToggle = document.createElement('button'); btnToggle.className='btn ' + (item.status === 'active' ? 'btn-danger' : 'btn-success'); btnToggle.textContent = (item.status === 'active' ? '暂停' : '启用');
        rowBtns.appendChild(btnEdit); rowBtns.appendChild(btnDelete); rowBtns.appendChild(btnReveal); rowBtns.appendChild(btnToggle);
        body.appendChild(rowBtns);
        wrap.appendChild(body);

        toggleBtn.addEventListener('click', function(){
          var open = body.style.display !== 'none';
          body.style.display = open ? 'none' : '';
          toggleBtn.textContent = open ? '展开' : '收起';
        });

        btnDelete.addEventListener('click', async function(){
          if (!confirm('确认删除该策略？')) return;
          try{
            var res = await window.AppApi.request('DELETE', '/scripts/' + item.id, null, true);
            if (res.ok || (res.status && res.status < 400)) { loadList(); return; }
            await window.AppApi.jsonOrThrow(await window.AppApi.request('POST','/scripts/' + item.id + '/delete', {}, true));
            loadList();
          }catch(err){}
        });

        btnEdit.addEventListener('click', function(){
          window.location.href = 'strategy-detail.html?id=' + encodeURIComponent(item.id);
        });

        btnReveal.addEventListener('click', function(){
          window.location.href = 'strategy-secret.html?id=' + encodeURIComponent(item.id);
        });

        btnToggle.addEventListener('click', async function(){
          var action = item.status === 'active' ? 'pause' : 'resume';
          btnToggle.disabled = true;
          try{
            await window.AppApi.jsonOrThrow(await window.AppApi.request('POST','/scripts/' + item.id + (action === 'resume' ? '/resume' : '/pause'), {}, true));
            item.status = action === 'pause' ? 'paused' : 'active';
            btnToggle.className = 'btn ' + (item.status === 'active' ? 'btn-danger' : 'btn-success');
            btnToggle.textContent = item.status === 'active' ? '暂停' : '启用';
            loadList();
          }catch(err){ btnToggle.disabled = false; }
        });

        listWrap.appendChild(wrap);
      })(items[i]);
    }
  }

  function buildFilterBar(){
    if (filterBar) return; filterBar = document.createElement('div'); filterBar.style.display='flex'; filterBar.style.gap='8px'; filterBar.style.margin='8px 0';
    function inp(ph, key, type){ var i=document.createElement(type==='select'?'select':'input'); i.className='input'; if(type!=='select') i.placeholder=ph; if(type==='select'){ var o0=document.createElement('option'); o0.value=''; o0.textContent=ph; i.appendChild(o0);} i.addEventListener('change', change); i.addEventListener('input', change); i.setAttribute('data-key', key); return i; }
    function change(){ var k=this.getAttribute('data-key'); var v=(this.value||'').trim(); state[k]=v; state.page=1; loadList(); }
    var nameI=inp('按名称', 'name'); var symI=inp('按符号', 'symbol');
    var mktI=inp('市场类型', 'market_type', 'select'); var o1=document.createElement('option'); o1.value='spot'; o1.textContent='spot'; var o2=document.createElement('option'); o2.value='perpetual'; o2.textContent='perpetual'; mktI.appendChild(o1); mktI.appendChild(o2);
    var stI=inp('状态', 'status', 'select'); ['active','paused'].forEach(function(v){ var o=document.createElement('option'); o.value=v; o.textContent=v; stI.appendChild(o); });
    var orderI=document.createElement('select'); orderI.className='input'; orderI.setAttribute('data-key','order');
    var od0=document.createElement('option'); od0.value='desc'; od0.textContent='创建时间：降序'; var od1=document.createElement('option'); od1.value='asc'; od1.textContent='创建时间：升序';
    orderI.appendChild(od0); orderI.appendChild(od1); orderI.addEventListener('change', change);
    orderI.value = state.order;
    filterBar.appendChild(nameI); filterBar.appendChild(symI); filterBar.appendChild(mktI); filterBar.appendChild(stI); filterBar.appendChild(orderI);
    viewCard.insertBefore(filterBar, listWrap);
  }

  function renderPager(data){
    if (!pagerBar){ pagerBar=document.createElement('div'); pagerBar.style.display='flex'; pagerBar.style.justifyContent='space-between'; pagerBar.style.alignItems='center'; pagerBar.style.marginTop='8px'; viewCard.appendChild(pagerBar); }
    var total = data && (data.total || data.count);
    var page = data && (data.page || state.page); var size = data && (data.page_size || state.page_size);
    pagerBar.innerHTML = '';
    var info=document.createElement('span'); info.className='muted small'; info.textContent = total ? ('第 ' + page + ' 页 · 共 ' + total + ' 条') : ('第 ' + page + ' 页');
    var controls=document.createElement('div'); controls.style.display='flex'; controls.style.gap='8px';
    var prev=document.createElement('button'); prev.className='btn'; prev.textContent='上一页'; prev.disabled = page <= 1; prev.addEventListener('click', function(){ state.page=Math.max(1, page-1); loadList(); });
    var next=document.createElement('button'); next.className='btn'; next.textContent='下一页'; var maxPage = total ? Math.ceil(total/size) : null; next.disabled = (maxPage && page>=maxPage); next.addEventListener('click', function(){ state.page = page + 1; if (maxPage) state.page = Math.min(maxPage, state.page); loadList(); });
    controls.appendChild(prev); controls.appendChild(next);
    pagerBar.appendChild(info); pagerBar.appendChild(controls);
  }

  // wiring
  entryCard.style.display = '';
  openBtn.addEventListener('click', async function(){
    var ok = await ensureAdminOrFail(); if (!ok) return;
    show(entryCard, false); show(viewCard, true); buildFilterBar(); loadList();
  });
  backBtn.addEventListener('click', function(){ show(viewCard, false); show(entryCard, true); });
  createBtn.addEventListener('click', function(){ window.location.href = 'strategy-create.html'; });
})();


